const jwt = require("jsonwebtoken");
const User = require("../models/users");
const config = require("../config");
const { formatSuccess } = require("../utils");

class UsersCtl {
  async checkOwner(ctx, next) {
    if (ctx.params.id !== ctx.state.user.__id) {
      ctx.throw(403, "没有权限");
    }
    await next();
  }
  // 查询所有
  async find(ctx) {
    const user = await User.find().select("+password");
    ctx.body = formatSuccess(user);
  }
  // 查询单个用户
  async findById(ctx) {
    const user = await User.findById(ctx.params.id);
    if (!user) {
      ctx.throw(404, "用户不存在");
    }
    ctx.body = formatSuccess(user);
  }
  // 注册
  async create(ctx) {
    ctx.verifyParams({
      name: {
        type: "string",
        required: true,
      },
      password: {
        type: "string",
        require: true,
      },
    });
    const { name } = ctx.request.body;
    // 查重
    const repeatedUser = await User.findOne({ name });
    if (repeatedUser) {
      ctx.throw(409, "用户已存在");
    }
    const user = await new User(ctx.request.body).save();
    ctx.body = formatSuccess(user);
  }
  // 更新
  async update(ctx) {
    ctx.verifyParams({
      name: {
        type: "string",
        required: false,
      },
      password: {
        type: "string",
        require: false,
      },
    });
    const user = await User.findByIdAndUpdate(ctx.params.id, ctx.request.body);
    if (!user) {
      ctx.throw(404, "用户不存在");
    }
    ctx.body = formatSuccess(user, "更新成功");
  }
  // 删除
  async deleteUser(ctx) {
    const user = await User.findByIdAndRemove(ctx.params.id);
    if (!user) {
      ctx.throw(404, "用户不存在");
    }
    ctx.body = formatSuccess();
  }
  // 登陆
  async login(ctx) {
    ctx.verifyParams({
      name: {
        type: "string",
        required: true,
      },
      password: {
        type: "string",
        require: true,
      },
    });
    const user = await User.findOne(ctx.request.body);
    if (!user) {
      ctx.throw(200, "用户名密码不正确");
    }
    const { _id, name } = user;
    const token = jwt.sign(
      {
        _id,
        name,
      },
      config.secret,
      { expiresIn: "1d" },
    );
    let res = {
      id:_id,
      name,
      token
    }
    ctx.body = formatSuccess(res)
  }
}

module.exports = new UsersCtl();
